package com.xyzwps.server.paimon.jackson

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonToken
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.KeyDeserializer
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import com.xyzwps.server.paimon.value.VcodeScene
import com.xyzwps.server.paimon.value.toVcodeScene

class VcodeSceneJacksonSerializer : StdSerializer<VcodeScene>(VcodeScene::class.java) {
    override fun serialize(value: VcodeScene?, gen: JsonGenerator, provider: SerializerProvider) {
        if (value == null) {
            gen.writeNull()
        } else {
            gen.writeNumber(value.value)
        }
    }
}

class VcodeSceneJacksonDeserializer : StdDeserializer<VcodeScene>(VcodeScene::class.java) {
    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): VcodeScene? =
        when (val token = p.currentToken) {
            JsonToken.VALUE_NULL -> null
            JsonToken.VALUE_NUMBER_INT -> p.intValue.toVcodeScene()
            else -> throw JsonMappingException.from(p, "Unexpected token $token")
        }
}

class VcodeSceneJacksonKeyDeserializer : KeyDeserializer() {
    override fun deserializeKey(key: String?, ctxt: DeserializationContext): Any? =
        key?.toInt()?.toVcodeScene()
}

fun SimpleModule.registerVcodeScene() {
    addSerializer(VcodeScene::class.java, VcodeSceneJacksonSerializer())
    addDeserializer(VcodeScene::class.java, VcodeSceneJacksonDeserializer())
    addKeySerializer(VcodeScene::class.java, VcodeSceneJacksonSerializer())
    addKeyDeserializer(VcodeScene::class.java, VcodeSceneJacksonKeyDeserializer())
}